package com.cysyz.commonservice.mycommonservice.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import lombok.Cleanup;

import com.cysyz.dao.BaseDao;

public class UploadFileServiceImpl {
	private static long maxSize = 1024 * 1024 * 5;
	@Resource BaseDao dao;
	public void upload(UploadFileAble uploadFileAble, List<String> allowTypes, String uploadFileName, byte[] uploadFileData, ) throws IllegalFileSizeException, IllegalFileTypeException {
		String type = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
		checkFileType(type, allowTypes);
		checkFileSize(uploadFileAble);
		String saveFilePath = null;
		uploadFileAble.setSaveFilePath(saveFilePath );
		dao.save(uploadFileAble);
		saveFileToLocal(uploadFileAble.getAbsoluteFilePath(), uploadFileAble.getFileData());
	}

	private void checkFileSize(UploadFileAble uploadFileAble)
			throws IllegalFileSizeException {
		if (uploadFileAble.getFileData().length > maxSize ) {
			throw new IllegalFileSizeException("file size too big: maxSize=" + maxSize);
		}
	}

	private void saveFileToLocal(String absoluteFilePath, byte[] fileData) {
		try {
			@Cleanup FileOutputStream fops = new FileOutputStream(new File(absoluteFilePath));
			fops.write(fileData);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} 
	}

	private void checkFileType(final String fileType, List<String> allowTypes) throws IllegalFileTypeException {
		for (String allowType : allowTypes) {
			if (allowType.toLowerCase().equals(fileType.toLowerCase())) {
				throw new IllegalFileTypeException("the type of file is not allowed:" + fileType);
			}
		}
	}
}
